import { Widget } from '@/models'
import { Viewer } from '@/types'

/** 控件点击事件，支持点击区域的多个控件 `widgets: Widget[], e: MouseEvent` */
export default function emitWidgetsClick(
  e: MouseEvent,
  widgets: Widget[],
  viewer: Viewer,
  isWidgetInPoint: (widget: Widget, px: number, py: number) => boolean
) {
  const { pageX, pageY } = e
  const { left, top } = (e.currentTarget as HTMLElement)?.getBoundingClientRect()
  const { level: zoom } = viewer.zoom

  const x = Math.floor((pageX - left) / zoom)
  const y = Math.floor((pageY - top) / zoom)

  // 点击区域的控件
  const widgetsInPoint = widgets.filter(w => isWidgetInPoint(w, x, y))

  if (widgetsInPoint.length) {
    viewer.$emit('widgets-click', widgetsInPoint, e)
  }
}
